package com.example.blog.controller;

import com.example.blog.constants.Constants;
import com.example.blog.model.Result;
import com.example.blog.model.UserInfo;
import com.example.blog.service.UserInfoService;
import com.example.blog.utils.JwtUtils;
import com.example.blog.utils.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户模块，负责用户信息的相关操作
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;


    /**
     *
     * @param userName 用户名
     * @param password 密码
     * @return 返回登录结果
     */
    @RequestMapping("/login")
    public Result<?> login(String userName, String password) {
        //校验参数
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码为空");
        }
        //获取用户信息
        UserInfo user = userInfoService.getUserByName(userName);
        if(user == null) {
            //todo
            user = userInfoService.register(userName, password);
            if(user == null) {
                return Result.fail("注册失败");
            }
        }
        //校验密码
        if(!SecurityUtils.verity(password, user.getPassword())) {
            return Result.fail("密码错误");
        }
        //生成token
        Map<String, Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_ID, user.getId());
        claim.put(Constants.TOKEN_USERNAME, user.getUserName());
        return Result.success(JwtUtils.genJwtToken(claim));
    }


    /**
     * 从token中获取用户信息
     * @param request
     * @return
     */
    @RequestMapping("/getUserInfo")
    public UserInfo getLoginUserInfo(HttpServletRequest request) {
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        return userInfoService.getUserById(JwtUtils.getIdInToken(token));
    }

    @RequestMapping("/getUserByName")
    public UserInfo getUserByName(String userName) {
        return userInfoService.getUserByName(userName);
    }

    /**
     * 通过博客id获取作者信息
     * @param blogId
     * @return
     */
    @RequestMapping("/getAuthorInfo")
    public Result<?> getAuthorInfo(Integer blogId) {
        UserInfo author = userInfoService.getAuthorInfo(blogId);
        if(author == null) {
            log.error("作者信息不存在：blogId:{}", blogId);
            return Result.fail("作者信息不存在");
        }
        return Result.success(author);
    }
}
